<template>
  <view class="settings">
    <view class="settings-section">
      <!-- 入职时间设置 -->
      <view class="setting-item">
        <view class="item-label">入职时间</view>
        <view class="input-wrapper">
          <picker 
            mode="date" 
            :value="settings.joinDate"
            start="2000-01-01"
            :end="today"
            @change="onJoinDateChange"
          >
            <view class="picker-value">
              {{ settings.joinDate }}
              <view class="picker-arrow">
                <view class="arrow-icon"></view>
              </view>
            </view>
          </picker>
        </view>
      </view>

      <!-- 薪资设置 -->
      <view class="setting-item">
        <view class="item-label">薪资类型</view>
        <view class="input-wrapper">
          <picker 
            mode="selector" 
            :range="salaryTypes" 
            :value="salaryTypeIndex"
            @change="onSalaryTypeChange"
          >
            <view class="picker-value">
              {{ salaryTypes[salaryTypeIndex] }}
              <view class="picker-arrow">
                <view class="arrow-icon"></view>
              </view>
            </view>
          </picker>
        </view>
      </view>
      
      <view class="setting-item">
        <view class="item-label">{{ salaryTypes[salaryTypeIndex] }}金额</view>
        <view class="input-wrapper">
          <text class="currency-symbol">¥</text>
          <input 
            type="digit" 
            :value="String(settings.salary.amount)"
            @input="onSalaryAmountChange"
            placeholder="请输入金额"
            class="salary-input"
          />
        </view>
      </view>

      <!-- 工作时间设置 -->
      <view class="setting-group">
        <view class="group-title">工作时间</view>
        <view class="time-settings">
          <view class="time-period">
            <text class="period-label">上午工作时间</text>
            <view class="time-range">
              <view class="time-picker">
                <text class="time-label">上班</text>
                <picker
                  mode="time"
                  :value="settings.morningStart"
                  @change="onMorningStartChange"
                >
                  <view class="picker-value">
                    {{ settings.morningStart }}
                    <view class="picker-arrow">
                      <view class="arrow-icon"></view>
                    </view>
                  </view>
                </picker>
              </view>
              <text class="time-separator">至</text>
              <view class="time-picker">
                <text class="time-label">下班</text>
                <picker
                  mode="time"
                  :value="settings.morningEnd"
                  @change="onMorningEndChange"
                >
                  <view class="picker-value">
                    {{ settings.morningEnd }}
                    <view class="picker-arrow">
                      <view class="arrow-icon"></view>
                    </view>
                  </view>
                </picker>
              </view>
            </view>
          </view>

          <view class="time-period">
            <text class="period-label">下午工作时间</text>
            <view class="time-range">
              <view class="time-picker">
                <text class="time-label">上班</text>
                <picker
                  mode="time"
                  :value="settings.afternoonStart"
                  @change="onAfternoonStartChange"
                >
                  <view class="picker-value">
                    {{ settings.afternoonStart }}
                    <view class="picker-arrow">
                      <view class="arrow-icon"></view>
                    </view>
                  </view>
                </picker>
              </view>
              <text class="time-separator">至</text>
              <view class="time-picker">
                <text class="time-label">下班</text>
                <picker
                  mode="time"
                  :value="settings.afternoonEnd"
                  @change="onAfternoonEndChange"
                >
                  <view class="picker-value">
                    {{ settings.afternoonEnd }}
                    <view class="picker-arrow">
                      <view class="arrow-icon"></view>
                    </view>
                  </view>
                </picker>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 发薪日设置 -->
      <view class="setting-group">
        <view class="group-title">发薪设置</view>
        <payday-picker
          v-model="paydaySettings"
          label="发薪时间"
          @input="onPaydaySettingsChange"
        />
      </view>

      <!-- 工作日设置 -->
      <view class="setting-group">
        <view class="group-title">工作日</view>
        <view class="weekday-selector">
          <view 
            v-for="day in weekdays" 
            :key="day.value"
            :class="['weekday-item', { active: settings.workdays.includes(day.value) }]"
            @tap="toggleWorkday(day.value)"
          >
            {{ day.label }}
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="settings-actions">
      <view class="save-button" @tap="saveSettings">保存设置</view>
      <view class="reset-button" @tap="resetSettings">重置默认</view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import Taro from '@tarojs/taro'
import eventBus from '../../utils/eventBus'
import store from '../../store'
import PaydayPicker from '../../components/PaydayPicker.vue'

const defaultSettings = {
  joinDate: new Date().toISOString().split('T')[0],
  salary: {
    type: 'monthly',
    amount: 18888
  },
  morningStart: '09:00',
  morningEnd: '12:00',
  afternoonStart: '13:30',
  afternoonEnd: '18:00',
  payday: 15,
  paydayTime: '12:00',
  workdays: [1, 2, 3, 4, 5]
}

export default {
  name: 'Settings',
  components: {
    PaydayPicker
  },
  data() {
    return {
      settings: {
        joinDate: new Date().toISOString().split('T')[0],
        salary: {
          type: 'monthly',
          amount: 18888
        },
        morningStart: '09:00',
        morningEnd: '12:00',
        afternoonStart: '13:30',
        afternoonEnd: '18:00',
        payday: 15,
        paydayTime: '12:00',
        workdays: [1, 2, 3, 4, 5]
      },
      salaryTypeIndex: 0,
      salaryTypes: ['月薪', '时薪'],
      weekdays: [
        { label: '一', value: 1 },
        { label: '二', value: 2 },
        { label: '三', value: 3 },
        { label: '四', value: 4 },
        { label: '五', value: 5 },
        { label: '六', value: 6 },
        { label: '日', value: 7 }
      ],
      payDays: Array.from({ length: 31 }, (_, i) => (i + 1).toString()),
      today: new Date().toISOString().split('T')[0],
      paydaySettings: {
        day: 15,
        time: '12:00'
      }
    }
  },
  computed: {
    ...mapState({
      storeSettings: state => state.workSettings
    })
  },
  created() {
    // 在组件创建时就加载设置
    if (this.storeSettings && Object.keys(this.storeSettings).length > 0) {
      this.settings = JSON.parse(JSON.stringify(this.storeSettings))
      this.salaryTypeIndex = this.settings.salary.type === 'monthly' ? 0 : 1
    }
  },
  mounted() {
    // 确保有默认值
    this.$store.dispatch('loadSettings')
  },
  methods: {
    onJoinDateChange(e) {
      this.settings.joinDate = e.detail.value
    },
    onSalaryTypeChange(e) {
      this.salaryTypeIndex = e.detail.value
      this.settings.salary.type = e.detail.value === 0 ? 'monthly' : 'hourly'
    },
    onSalaryAmountChange(e) {
      this.settings.salary.amount = parseFloat(e.detail.value) || 0
    },
    onMorningStartChange(e) {
      const start = e.detail.value
      // 如果还没有设置结束时间，直接设置开始时间
      if (!this.settings.morningEnd) {
        this.settings.morningStart = start
        return
      }
      
      const startTime = this.getMinutesFromTime(start)
      const endTime = this.getMinutesFromTime(this.settings.morningEnd)
      
      if (startTime >= endTime) {
        Taro.showToast({
          title: '上班时间必须早于下班时间',
          icon: 'none'
        })
        return
      }
      
      this.settings.morningStart = start
    },
    onMorningEndChange(e) {
      const end = e.detail.value
      // 如果还没有设置开始时间，直接设置结束时间
      if (!this.settings.morningStart) {
        this.settings.morningEnd = end
        return
      }
      
      const startTime = this.getMinutesFromTime(this.settings.morningStart)
      const endTime = this.getMinutesFromTime(end)
      
      if (endTime <= startTime) {
        Taro.showToast({
          title: '下班时间必须在上班时间之后',
          icon: 'none'
        })
        return
      }
      
      this.settings.morningEnd = end
    },
    onAfternoonStartChange(e) {
      const start = e.detail.value
      // 如果还没有设置结束时间，直接设置开始时间
      if (!this.settings.afternoonEnd) {
        this.settings.afternoonStart = start
        return
      }
      
      const startTime = this.getMinutesFromTime(start)
      const endTime = this.getMinutesFromTime(this.settings.afternoonEnd)
      
      if (startTime >= endTime) {
        Taro.showToast({
          title: '上班时间必须早于下班时间',
          icon: 'none'
        })
        return
      }
      
      this.settings.afternoonStart = start
    },
    onAfternoonEndChange(e) {
      const end = e.detail.value
      // 如果还没有设置开始时间，直接设置结束时间
      if (!this.settings.afternoonStart) {
        this.settings.afternoonEnd = end
        return
      }
      
      const startTime = this.getMinutesFromTime(this.settings.afternoonStart)
      const endTime = this.getMinutesFromTime(end)
      
      if (endTime <= startTime) {
        Taro.showToast({
          title: '下班时间必须在上班时间之后',
          icon: 'none'
        })
        return
      }
      
      this.settings.afternoonEnd = end
    },
    getMinutesFromTime(timeString) {
      if (!timeString) return 0
      const [hours, minutes] = timeString.split(':').map(Number)
      return hours * 60 + minutes
    },
    onPaydaySettingsChange(value) {
      this.settings.payday = value.day
      this.settings.paydayTime = value.time
    },
    toggleWorkday(day) {
      // 至少保留一个工作日
      if (this.settings.workdays.length === 1 && this.settings.workdays.includes(day)) {
        return
      }
      
      const index = this.settings.workdays.indexOf(day)
      if (index === -1) {
        this.settings.workdays.push(day)
        this.settings.workdays.sort((a, b) => a - b)
      } else {
        this.settings.workdays.splice(index, 1)
      }
    },
    saveSettings() {
      // 直接保存完整的设置对象
      const settings = { ...this.settings }
      
      this.$store.dispatch('saveSettings', settings)
        .then(() => {
          Taro.showToast({
            title: '设置已保存',
            icon: 'success',
            duration: 2000
          })
          // 通知首页更新数据
          eventBus.$emit('settings-updated')
        })
    },
    resetSettings() {
      Taro.showModal({
        title: '提示',
        content: '确定要重置所有设置吗？',
        success: (res) => {
          if (res.confirm) {
            this.settings = JSON.parse(JSON.stringify(defaultSettings))
            this.salaryTypeIndex = 0
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.settings {
  min-height: 100vh;
  background: #f8fafc;
  padding: 16px;

  .settings-section {
    background: #fff;
    border-radius: 24px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);

    .setting-group {
      margin-bottom: 32px;
      
      .group-title {
        font-size: 20px;
        color: #64748b;
        margin-bottom: 16px;
        font-weight: 500;
      }
    }
  }

  .setting-item {
    margin-bottom: 28px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .item-label {
      font-size: 19px;
      color: #64748b;
      font-weight: 500;
      flex-shrink: 0;
    }

    .input-wrapper {
      position: relative;
      display: flex;
      align-items: center;
      background: #fff;
      border: 1px solid #e2e8f0;
      border-radius: 16px;
      transition: all 0.2s ease;
      overflow: hidden;
      width: 65%;
      
      &:focus-within {
        border-color: #3b82f6;
        box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
      }
      
      .currency-symbol {
        padding: 0 0 0 16px;
        color: #64748b;
        font-size: 16px;
      }
    }

    .picker-value {
      height: 52px;
      line-height: 52px;
      padding: 0 20px;
      font-size: 19px;
      color: #1e293b;
      display: flex;
      justify-content: space-between;
      align-items: center;
      transition: all 0.3s ease;

      &:active {
        background: rgba(59, 130, 246, 0.05);
      }

      .picker-arrow {
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 12px;
        background: #f1f5f9;
        margin-left: 8px;
        
        .arrow-icon {
          font-size: 18px;
          color: #64748b;
          position: relative;
          width: 12px;
          height: 12px;
          &::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 6px;
            height: 6px;
            border-right: 2px solid #64748b;
            border-bottom: 2px solid #64748b;
            transform: translate(-50%, -75%) rotate(45deg);
          }
        }
      }
    }

    .salary-input {
      height: 52px;
      padding: 0 20px;
      font-size: 19px;
      border: none;
      outline: none;
      flex: 1;
      color: #1e293b;
      
      &::placeholder {
        color: #94a3b8;
      }
      
      &:disabled {
        background: #f8fafc;
        color: #64748b;
      }
    }
  }

  .weekday-selector {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    padding: 4px;

    .weekday-item {
      width: 52px;
      height: 52px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 16px;
      background: #fff;
      border: 1px solid #e2e8f0;
      font-size: 20px;
      color: #64748b;
      transition: all 0.3s ease;
      font-weight: 500;

      &.active {
        background: #3b82f6;
        color: white;
        border-color: #3b82f6;
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
      }

      &:active {
        transform: scale(0.95);
        opacity: 0.9;
      }
    }
  }

  .settings-actions {
    display: flex;
    flex-direction: column;
    gap: 16px;
    padding: 0 20px;

    .save-button {
      background: #3b82f6;
      color: white;
      height: 52px;
      line-height: 52px;
      text-align: center;
      border-radius: 24px;
      font-size: 20px;
      font-weight: 500;
      box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }
    }

    .reset-button {
      background: #f1f5f9;
      color: #64748b;
      height: 52px;
      line-height: 52px;
      text-align: center;
      border-radius: 24px;
      font-size: 20px;
      transition: all 0.3s ease;

      &:active {
        background: #e2e8f0;
      }
    }
  }

  .setting-group .weekday-selector {
    width: 100%;
    margin-top: 16px;
  }

  .time-settings {
    .time-period {
      margin-bottom: 24px;
      
      .period-label {
        font-size: 16px;
        color: #64748b;
        margin-bottom: 16px;
        display: block;
      }
      
      .time-range {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .time-picker {
          flex: 1;
          
          .time-label {
            font-size: 14px;
            color: #64748b;
            margin-bottom: 8px;
            display: block;
          }
          
          .picker-value {
            height: 48px;
            line-height: 48px;
            padding: 0 16px;
            font-size: 17px;
            color: #1e293b;
            background: #f8fafc;
            border-radius: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
            
            &:active {
              background: rgba(59, 130, 246, 0.05);
            }
          }
        }
        
        .time-separator {
          font-size: 16px;
          color: #64748b;
          padding: 0 4px;
          margin-top: 32px;
        }
      }
    }
  }
}
</style> 